package com.ghn.cocknovel.net.task

import com.ghn.cocknovel.ext.getUserAccount
import com.ghn.cocknovel.ext.getUserPassWord
import com.ghn.cocknovel.ext.setIsLogin
import com.ghn.cocknovel.net.DataService
import com.google.gson.Gson
import com.kt.NetworkModel.bean.LoginBean
import com.kt.NetworkModel.net.CallBack
import com.kt.NetworkModel.net.RxUtils
import com.kt.NetworkModel.utils.MLog
import com.kt.NetworkModel.utils.MVUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 *@author: Administrator
 *2023/10/16
 *desc:
 */
object LoginTask {
    private var disposable: Disposable? = null
    fun startTask() {
        disposable = Observable.interval(15L, 60 * 5, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                MLog.d("----------------心跳登陆--------------------")
                loginNet()
            }) {
                MLog.d("心跳错误-->" + it.message)
            }

    }

    /**
     * 停止定时执行
     */
    fun stopTask() {
        if (null != disposable) {
            disposable!!.dispose()
            disposable = null
        }
    }

    fun loginNet() {
        DataService.login(MVUtils.getUserAccount() + "", MVUtils.getUserPassWord() + "").compose(RxUtils.mainSync()).subscribe(object : CallBack<LoginBean>() {
            override fun onResult(result: LoginBean?) {
                result?.also {
                    MVUtils.put("userData", Gson().toJson(result))
                    MVUtils.setIsLogin(true)
                }
            }
        })
    }

}